import React, { useState, useRef } from 'react';
import PropTypes from 'prop-types';
import { Menu, Dropdown, Popconfirm } from 'antd';
import cn from 'classnames';
import './index.less';

const MenuItem = Menu.Item;

const MyDropdown = props => {
  const moreRef = useRef(null);
  const { title, menus, disabled = false } = props;
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const [popconfirmVisible, setPopconfirmVisible] = useState(-1);
  const onMenuClick = e => {
    e.domEvent.stopPropagation();
    if (popconfirmVisible !== e.key) {
      setPopconfirmVisible(e.key);
    }
  };

  const wrapConfirm = (confirm, closeDropdownBeforeConfirm) => e => {
    e.stopPropagation();
    if (closeDropdownBeforeConfirm) {
      setDropdownVisible(false);
      setPopconfirmVisible(-1);
    }
    if (confirm instanceof Function) {
      confirm();
    }
    setPopconfirmVisible(-1);
  };

  const dropdownMenu = (
    <Menu onClick={onMenuClick}>
      {menus.map((menu, index) =>
        !menu.disabled ? (
          <MenuItem key={index}>
            {menu.disableConfirm ? (
              <span
                className={cn('menu-item', menu.className)}
                onClick={wrapConfirm(menu.onConfirm, menu.closeDropdownBeforeConfirm)}
              >
                {menu.title}
              </span>
            ) : (
              <Popconfirm
                overlayClassName="popconfirm"
                title={menu.info}
                visible={popconfirmVisible === index.toString()}
                getPopupContainer={() => moreRef.current}
                onCancel={() => setPopconfirmVisible(-1)}
                onConfirm={wrapConfirm(menu.onConfirm, menu.closeDropdownBeforeConfirm)}
              >
                <span className={cn('menu-item', menu.className)}>{menu.title}</span>
              </Popconfirm>
            )}
          </MenuItem>
        ) : null
      )}
    </Menu>
  );
  const onDropdownVisibleChange = visible => {
    setPopconfirmVisible(-1);
    setDropdownVisible(visible);
  };

  return (
    <div className="my-dropdown-wrapper" onClick={e => e.stopPropagation()}>
      <Dropdown
        overlayClassName="my-dropdown"
        overlay={dropdownMenu}
        visible={dropdownVisible}
        onVisibleChange={onDropdownVisibleChange}
        getPopupContainer={() => moreRef.current}
        disabled={disabled}
      >
        <span className={cn('title', { disabled }, 'be-color')} ref={moreRef}>
          {title}
        </span>
      </Dropdown>
    </div>
  );
};

MyDropdown.propTypes = {
  title: PropTypes.string,
  menus: PropTypes.arrayOf(
    PropTypes.shape({
      title: PropTypes.string,
      info: PropTypes.string,
      disableConfirm: PropTypes.bool,
      onConfirm: PropTypes.func,
      closeDropdownBeforeConfirm: PropTypes.oneOfType([PropTypes.func, PropTypes.bool])
    })
  ),
  disabled: PropTypes.bool
};

export default MyDropdown;
